package org.quality4spl.fm;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.quality4spl.fm.cvm.ConfigDecision;
import org.quality4spl.fm.cvm.ConfigDecisionModelEntry;
import org.quality4spl.fm.cvm.CvmPackage;
import org.quality4spl.fm.cvm.FeatureConfiguration;
import org.quality4spl.fm.cvm.VariabilityModel;
import org.quality4spl.fm.cvm.VariabilityModelEntry;

public class CVMModelWrapper implements FMWrapper{
	
	static{
		// register default ePackages
		if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("ecore"))
			Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
				"ecore", new EcoreResourceFactoryImpl());
		if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("xmi"))
			Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
				"xmi", new XMIResourceFactoryImpl());
		
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
				"cvm", new XMIResourceFactoryImpl());
		CvmPackage.eINSTANCE.getEFactoryInstance();
	}
	
	private VariabilityModel model;
	private ResourceSet rSet = new ResourceSetImpl();
	
	public CVMModelWrapper(URI modelURI) {
		model = (VariabilityModel) rSet.getResource(modelURI, true)
		  .getContents().get(0);
	}
	
	public VariabilityModel getSourceModel(){
		return model;
	}
	
	public List<String> getSelectedFeatures(){
		List<String> selFeatures = new ArrayList<String>();
		for(VariabilityModelEntry entry : model.getRootEntries()){
			if( false == entry instanceof FeatureConfiguration)
				continue;
			for(ConfigDecisionModelEntry config :((FeatureConfiguration)entry).getRootEntries()){
				if( false ==config instanceof ConfigDecision)
					continue;
				if(((ConfigDecision)config).getIncludedFeatures() != null){
					selFeatures.add(((ConfigDecision)config).getIncludedFeatures().replaceFirst("\\[.\\]", "")
							.replace("\"", "").replaceFirst("=.*$", ""));
				}
			}
		}
		return selFeatures;
	}

}
